package main.java.DMDE.persistence;

import main.java.DMDE.model.*;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public abstract class EntityWithStateXmlManager extends EntityXmlManager {

	protected ModifierXmlManager modifierManager = new ModifierXmlManager();
	protected AttributeXmlManager attributeManager = new AttributeXmlManager();
	
	
	protected void fillElement(Element entityElement, Entity entity, Document document) {
		super.fillElement(entityElement, entity, document);
		EntityWithState statefulEntity = (EntityWithState) entity;
		if (statefulEntity.getVisibility() != null)
			entityElement.setAttribute("visibility", statefulEntity.getVisibility() != null ? statefulEntity.getVisibility().getType() : Visibility.PUBLIC.getType());
		Element modifiers = document.createElement("modifiers");
		for (Modifier modifier : statefulEntity.getModifiers()) {
			modifiers.appendChild(modifierManager.getElementFromItem(modifier, document));
		}
		entityElement.appendChild(modifiers);
		Element attributes = document.createElement("attributes");
		for (Attribute attribute : statefulEntity.getAttributes()) {
			attributes.appendChild(attributeManager.getElementFromItem(attribute, document));
		}
		entityElement.appendChild(attributes);
	}

	protected void fillEntity(Entity entity, Element entityElement) throws Exception {
		super.fillEntity(entity, entityElement);
		EntityWithState statefulEntity = (EntityWithState) entity;
		statefulEntity.setVisibility(getVisibility(entityElement.getAttribute("visibility")));
		NodeList modifierElem = entityElement.getElementsByTagName("modifiers");
		NodeList modifiers = modifierElem.item(0) != null ? modifierElem.item(0).getChildNodes() : null;
		if (modifiers != null) for (int i = 0; i < modifiers.getLength(); i++) {
			Node node = modifiers.item(i);
			if (node == null || !(node instanceof Element))
				continue;
			statefulEntity.addModifier(modifierManager.getItemFromXmlElement((Element) node));
		}
		NodeList attributesElem = entityElement.getElementsByTagName("attributes");
		NodeList attributes = attributesElem.item(0) != null? attributesElem.item(0).getChildNodes() : null;
		if (attributes != null) for (int i = 0; i < attributes.getLength(); i++) {
			Node node = attributes.item(i);
			if (node == null || !(node instanceof Element))
				continue;
			statefulEntity.addAttribute(attributeManager.getItemFromXmlElement((Element) node));
		}
	}
	
	private Visibility getVisibility(String visibility) {
		if (Visibility.PUBLIC.getType().equals(visibility))
			return Visibility.PUBLIC;
		if (Visibility.PRIVATE.getType().equals(visibility))
			return Visibility.PRIVATE;
		if (Visibility.PROTECTED.getType().equals(visibility))
			return Visibility.PROTECTED;
		return Visibility.PROTECTED;
	}
}
